package com.ruoyi.project.port.service;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.project.bas.basCustomer.domain.BasCustomer;
import com.ruoyi.project.bas.basCustomer.mapper.BasCustomerMapper;
import com.ruoyi.project.bas.basJobId.service.IBasJobIdService;
import com.ruoyi.project.bas.basSupplier.domain.BasSupplier;
import com.ruoyi.project.bas.basSupplier.mapper.BasSupplierMapper;
import com.ruoyi.project.bas.product.domain.BasProduct;
import com.ruoyi.project.bas.product.mapper.BasProductMapper;
import com.ruoyi.project.bas.productMap.domain.ProductMap;
import com.ruoyi.project.bas.productMap.mapper.ProductMapMapper;
import com.ruoyi.project.in.stockin.domain.Stockin;
import com.ruoyi.project.in.stockin.mapper.StockinMapper;
import com.ruoyi.project.in.stockin.service.IStockinService;
import com.ruoyi.project.in.stockindetail.domain.StockinDetail;
import com.ruoyi.project.in.stockindetail.mapper.StockinDetailMapper;
import com.ruoyi.project.interface_log.domain.InterfaceLog;
import com.ruoyi.project.interface_log.mapper.InterfaceLogMapper;
import com.ruoyi.project.out.outStock.domain.OutStockout;
import com.ruoyi.project.out.outStock.mapper.OutStockoutMapper;
import com.ruoyi.project.out.outStockDetail.domain.OutStockoutDetail;
import com.ruoyi.project.out.outStockDetail.mapper.OutStockoutDetailMapper;
import com.ruoyi.project.port.domain.*;
import com.ruoyi.project.port.mapper.BackInOrderMapper;
import com.ruoyi.project.stock.stock.domain.BasStock;
import com.ruoyi.project.stock.stock.service.IBasStockService;
import com.ruoyi.project.util.JsonUtil;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PortServiceImpl implements PortService {

    @Autowired
    InterfaceLogMapper interfaceLogMapper;

    @Autowired
    BasProductMapper basProductMapper;
    @Autowired
    BasCustomerMapper basCustomerMapper;
    @Autowired
    BasSupplierMapper basSupplierMapper;
    @Autowired
    private IStockinService stockinService;
    @Autowired
    private StockinMapper stockinMapper;
    @Autowired
    private StockinDetailMapper stockinDetailMapper;
    @Autowired
    private IBasJobIdService basJobIdService;
    @Autowired
    private OutStockoutMapper outStockoutMapper;
    @Autowired
    private OutStockoutDetailMapper outStockoutDetailMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private BackInOrderMapper backInOrderMapper;
    @Autowired
    private IBasStockService basStockService;
    @Autowired
    private ProductMapMapper productMapMapper;


    /**
     * @Description: 基础信息物料 <br/>                                                                                                                               />
     * @author: zyr <br/>
     * @date: 2023/8/22 15:19 <br/>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertProduct(StockinDetail stockinDetail) {
        Result result = new Result();
        try {

            BasProduct basProduct1 = basProductMapper.selectBasProductByProductId(stockinDetail.getProductId());
            if (basProduct1 == null) {
                BasProduct basProduct = new BasProduct();
                basProduct.setProductUnit(stockinDetail.getUnit());
                basProduct.setProductsUsingFinished("1");
                basProduct.setProductId(stockinDetail.getProductId());
                basProduct.setProductName(stockinDetail.getProductName());
                basProduct.setModel(stockinDetail.getModel());
                basProduct.setUnit(stockinDetail.getUnit());
                basProduct.setProductGuid(UUID.randomUUID().toString());
                basProductMapper.insertBasProduct(basProduct);
                result.setCode(0);
                result.setMsg("操作成功！");
                insertLog("ProductInterface", basProduct.toString(), result.toString());
            } else {
                result.setCode(0);
                result.setMsg("物料已存在！");
            }
        } catch (Exception e) {
            result.setCode(1);
            result.setMsg("操作失败！" + e.getMessage());
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            insertLog("ProductInterface", stockinDetail.toString(), result.toString() + e.getMessage());
        }
        return result;
    }

    /**
     * @Description:基础信息客户 <br/>
     * @author: zyr <br/>
     * @date: 2023/8/22 15:19 <br/>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertCustomer(OutStockoutDetail outStockoutDetail) {
        Result result = new Result();
        try {
            BasCustomer basCustomer1 = basCustomerMapper.selectBasCustomerByCustomerNo(outStockoutDetail.getCustomerId());
            if (basCustomer1 == null) {
                BasCustomer basCustomer = new BasCustomer();
                basCustomer.setCustomerNo(outStockoutDetail.getCustomerId());
                basCustomer.setCustomerName(outStockoutDetail.getCustomerName());
                basCustomer.setUseable("1");
                basCustomer.setId(UUID.randomUUID().toString());
                basCustomerMapper.insertBasCustomer(basCustomer);
                result.setCode(0);
                result.setMsg("操作成功！");
                insertLog("CustomerInterface", basCustomer.toString(), result.toString());
            } else {
                result.setCode(0);
                result.setMsg("客户信息已存在！");
            }
        } catch (Exception e) {
            result.setCode(1);
            result.setMsg("操作失败！" + e.getMessage());
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            insertLog("CustomerInterface", outStockoutDetail.toString(), result.toString() + e.getMessage());
        }

        return result;
    }


    /**
     * @Description: 基础信息供应商<br />
     * @author: zyr <br/>
     * @date: 2023/8/23 9:08 <br/>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertSupplier(StockinDetail stockinDetail) {
        Result result = new Result();
        try {
            BasSupplier basSupplier1 = basSupplierMapper.selectBasSupplierBySupplierNo(stockinDetail.getSupplierId());
            if (basSupplier1 == null) {
                BasSupplier basSupplier = new BasSupplier();
                basSupplier.setSupplierNo(stockinDetail.getSupplierId());
                basSupplier.setSupplierName(stockinDetail.getSupplierName());
                basSupplier.setUseable("1");
                basSupplier.setId(UUID.randomUUID().toString());
                basSupplierMapper.insertBasSupplier(basSupplier);
                result.setCode(0);
                result.setMsg("操作成功！");
                insertLog("SupplierInterface", basSupplier.toString(), result.toString());
            } else {
                result.setCode(0);
                result.setMsg("供应商信息已存在！");
            }
        } catch (Exception e) {
            result.setCode(1);
            result.setMsg("操作失败！" + e.getMessage());
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            insertLog("SupplierInterface", stockinDetail.toString(), result.toString() + e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 下发入库单<br />
     * @author: zyr <br/>
     * @date: 2023/8/23 14:22 <br/>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertInOrder(InOrderMsg inOrderMsg) {
        Result result = new Result();
        try {
            // 往productMap表中添加数据
            List<StockinDetail> detailList1 = inOrderMsg.getDetailList();
            if (detailList1 != null && detailList1.size() !=0 ) {
                for (StockinDetail stockinDetail : detailList1) {
                    // 获取混淆码
                    String uniqueCode = stockinDetail.getUniqueCode();
                    // 获取物料码
                    String productId = stockinDetail.getProductId();
                    ProductMap productMap = new ProductMap();
                    productMap.setProductDetailId(uniqueCode);
                    productMap.setProductId(productId);
                    if (uniqueCode == null || "".equals(uniqueCode) || "null".equals(uniqueCode)){
                        continue;
                    }
                    // 先查看本来的表中有没有和上面传过来的相同的物料编码和混淆码
                    List<ProductMap> productMaps = productMapMapper.selectProductMapList(productMap);
                    if (productMaps.size() == 0) {
                        // 没查到再插入数据
                        productMap.setId(UUID.randomUUID().toString());
                        productMapMapper.insertProductMap(productMap);
                    }
                }
            }

            // 数据校验 检查子单数据是否为空 为空则不建单
            List<StockinDetail> detailList = inOrderMsg.getDetailList();
            if (detailList == null || detailList.size() == 0){
                // 不建单
                result.setCode(1);
                result.setMsg("子单数据缺失 操作失败！");
                insertLog("下发入库单 子单数据缺失 操作失败", inOrderMsg.toString(), result.toString() + "子单数据缺失 操作失败！");
                return result;
            }
            Stockin stockin1 = stockinMapper.selectStockinByFID(inOrderMsg.getReqCode());
            if ("1".equals(inOrderMsg.getOperationType())) {
                if (stockin1 == null) {
                    Stockin stockin = new Stockin();
                    String inStockId = stockinService.getStockInId();
                    String guid = java.util.UUID.randomUUID().toString();
                    stockin.setStockinGuid(guid);
                    stockin.setStockinId(inStockId);
                    stockin.setWarehouseId("01");
                    stockin.setStatus("1");// 1入库开单  2审核 3收货确认
                    stockin.setStockinSource("1");
                    stockin.setCreateDate(inOrderMsg.getCreateTime());
                    stockin.setCreateManId(inOrderMsg.getConstructor());
                    stockin.setFID(inOrderMsg.getReqCode());
                    stockin.setInType(inOrderMsg.getOrderType());
                    stockin.setStockinDId(inOrderMsg.getStockinDId());
                    stockin.setCreateby(inOrderMsg.getCreateby());
                    stockin.setFactory(inOrderMsg.getFactory());
                    stockin.setCustomerId(inOrderMsg.getCustomers());
                    stockin.setClassNowId(inOrderMsg.getDepartment());//天地煤机和研究院
                    stockinMapper.insertStockin(stockin);
                    int index = 0;

                    for (StockinDetail stockinDetail : inOrderMsg.getDetailList()) {
                        insertSupplier(stockinDetail);
                        insertProduct(stockinDetail);
                        index++;
                        stockinDetail.setStockinDetailId(inStockId + "-" + index);
                        stockinDetail.setStockinId(inStockId);
                        stockinDetail.setStockinGuid(guid);
                        stockinDetail.setStockStatus(stockinDetail.getProductStatus());
                        stockinDetail.setAssignNum(new BigDecimal(org.apache.commons.lang3.StringUtils.isBlank(stockinDetail.getWeight())?"0":stockinDetail.getWeight()));
                        stockinDetail.setPrintDate(stockinDetail.getProductionTime());
                        //WMS 纸质单的单号
                        /*if( org.apache.commons.lang3.StringUtils.isNotBlank(inOrderMsg.getStockinDId())){
                            stockinDetail.setProductGuid(inOrderMsg.getStockinDId());
                        }else {

                        }*/
                        stockinDetail.setProductGuid(inOrderMsg.getReqCode());
                        stockinDetailMapper.insertStockinDetail(stockinDetail);
                    }
                }
            }

            if ("3".equals(inOrderMsg.getOperationType())) {
                if (stockin1 != null) {
                    stockinMapper.deleteStockin(stockin1.getStockinGuid());
                    stockinDetailMapper.deleteStockinDetailByGuId(stockin1.getStockinGuid());
                }
            }
            result.setCode(0);
            result.setMsg("操作成功！");
            insertLog("操作成功InOrderInterface", inOrderMsg.toString(), result.toString());
        } catch (Exception e) {
            result.setCode(1);
            result.setMsg("操作失败！" + e.getMessage());
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            insertLog("操作失败InOrderInterface", inOrderMsg.toString(), result.toString() + e.getMessage());
        }
        return result;
    }


    /**
     * @Description: 出库单下发<br />
     * @author: zyr <br/>
     * @date: 2023/8/23 16:40 <br/>
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertOutOrder(OutOrderMsg outOrderMsg) {
        Result result = new Result();
        try {
            OutStockout outStockout1 = outStockoutMapper.selectOutStockoutByFID(outOrderMsg.getReqCode());

            if ("1".equals(outOrderMsg.getOperationType())) {
                if (outStockout1 == null) {
                    OutStockout outStockout = new OutStockout();
                    String stockoutId = basJobIdService.getJobId("CD");
                    outStockout.setStockoutGuid(java.util.UUID.randomUUID().toString());
                    outStockout.setStockoutId(stockoutId);
                    outStockout.setStatus("1");
                    outStockout.setWarehouseId("01");
                    outStockout.setOutType(outOrderMsg.getOrderType());
                    outStockout.setCreateManId(outOrderMsg.getConstructor());
                    outStockout.setCreateDate(outOrderMsg.getCreateTime());
                    outStockout.setCarNumber(outOrderMsg.getPriority());
                    outStockout.setFID(outOrderMsg.getReqCode());
                    outStockout.setStockoutSource("1");
                    outStockout.setFactory(outOrderMsg.getFactory());
                    outStockout.setDepartmentNo(outOrderMsg.getDepartment());//天地煤机和研究院
                    outStockoutMapper.insertOutStockout(outStockout);
                    int index = 0;
                    for (OutStockoutDetail outStockoutDetail : outOrderMsg.getDetailList()) {
                        index++;
                        insertCustomer(outStockoutDetail);
                        outStockoutDetail.setStockoutGuid(outStockout.getStockoutGuid());
                        outStockoutDetail.setStockoutId(outStockout.getStockoutId());
                        outStockoutDetail.setStockoutDetailId(outStockout.getStockoutId() + "-" + index);
                        outStockoutDetail.setPrice(outStockoutDetail.getProductStatus());
                        outStockoutDetail.setQuantityX(BigDecimal.ZERO);
                        outStockoutDetail.setQuantityJ(BigDecimal.ZERO);
                        //outStockoutDetail.setQuantityX(outStockoutDetail.getWeight());
                        outStockoutDetail.setEntryid(outStockoutDetail.getSupplierId());
                        outStockoutDetail.setOutId(outStockoutDetail.getCustomerId());
                        outStockoutDetail.setUnitName(outStockoutDetail.getProductTime());
                        outStockoutDetail.setAllotQuantity(BigDecimal.ZERO);
                        outStockoutDetail.setAssignNum(BigDecimal.ZERO);
                        outStockoutDetail.setCustomerId(outOrderMsg.getReqCode());
                        outStockoutDetail.setBukechaiQuantity(outStockoutDetail.getCustomerName());
                        outStockoutDetailMapper.insertOutStockoutDetail(outStockoutDetail);
                    }
                }
            }
            if ("3".equals(outOrderMsg.getOperationType())) {
                if (outStockout1 != null) {
                    outStockoutMapper.deleteOutStockoutByStockoutGuid(outStockout1.getStockoutGuid());
                    outStockoutDetailMapper.deleteOutStockoutDetailByStockoutId(outStockout1.getStockoutId());
                }
            }
            result.setCode(0);
            result.setMsg("操作成功！");
            insertLog("OutOrderInterface", outOrderMsg.toString(), result.toString());
        } catch (Exception e) {
            result.setCode(1);
            result.setMsg("操作失败！" + e.getMessage());
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            insertLog("OutOrderInterface", outOrderMsg.toString(), result.toString() + e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 暂存单入库 <br/>
     * @author: zyr <br/>
     * @date: 2023/8/24 16:16 <br/>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertDepositInOrder(DepositOrderMsg depositOrderMsg) {
        Result result = new Result();
        try {
            Stockin stockin1 = stockinMapper.selectStockinByFID(depositOrderMsg.getReqCode());
            if (stockin1 == null) {
                Stockin stockin = new Stockin();
                String inStockId = stockinService.getStockInId();
                String guid = java.util.UUID.randomUUID().toString();
                stockin.setStockinGuid(guid);
                stockin.setStockinId(inStockId);
                stockin.setWarehouseId("01");
                stockin.setStatus("1");// 1入库开单  2审核 3收货确认
                stockin.setStockinSource("1");
                stockin.setFID(depositOrderMsg.getReqCode());
                stockin.setLineId(depositOrderMsg.getOrderId());

                stockin.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                //获取当前操作员
                //todo 解开注释

//                SysUser user = (SysUser) ServletUtils.getSubject().getPrincipal();
//                String userName = user.getUserName();
                stockin.setCreateManId("ERP");
                stockin.setInType("9");
                stockinMapper.insertStockin(stockin);
                int index = 0;
                for (DepositOrderDetail detail : depositOrderMsg.getDetailList()) {
                    index++;
                    StockinDetail stockinDetail = new StockinDetail();
                    stockinDetail.setStockinDetailId(inStockId + "-" + index);
                    stockinDetail.setStockinId(inStockId);
                    stockinDetail.setStockinGuid(guid);
                    stockinDetail.setProductId(detail.getProductId());
                    stockinDetail.setCargoNo(detail.getTrayCode());
                    stockinDetailMapper.insertStockinDetail(stockinDetail);
                }
            }
            result.setCode(0);
            result.setMsg("操作成功！");
            insertLog("DepositInOrder", depositOrderMsg.toString(), result.toString());
        } catch (Exception e) {
            System.out.println(e);
            result.setCode(1);
            result.setMsg("操作失败！" + e.getMessage());
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            insertLog("DepositInOrderError", depositOrderMsg.toString(), result.toString() + e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 暂存单出库 <br/>
     * @author: zyr <br/>
     * @date: 2023/8/24 16:16 <br/>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertDepositOutOrder(DepositOrderMsg depositOrderMsg) {
        Result result = new Result();
        try {
            OutStockout outStockout1 = outStockoutMapper.selectOutStockoutByFID(depositOrderMsg.getReqCode());
            if (outStockout1 == null) {
                OutStockout outStockout = new OutStockout();
                String stockoutId = basJobIdService.getJobId("CD");
                outStockout.setStockoutGuid(java.util.UUID.randomUUID().toString());
                outStockout.setStockoutId(stockoutId);
                outStockout.setStatus("1");
                outStockout.setWarehouseId("01");
                outStockout.setStockoutSource("1");
                outStockout.setCreateDate(new SimpleDateFormat("yyyy-MM-dd hh:MM:ss").format(new Date()));
                outStockout.setFID(depositOrderMsg.getReqCode());
                outStockout.setErpStockoutId(depositOrderMsg.getOrderId());
                outStockout.setOutType("3");
                outStockoutMapper.insertOutStockout(outStockout);
                int index = 0;
                for (DepositOrderDetail detail : depositOrderMsg.getDetailList()) {
                    index++;
                    OutStockoutDetail outStockoutDetail = new OutStockoutDetail();
                    outStockoutDetail.setStockoutGuid(outStockout.getStockoutGuid());
                    outStockoutDetail.setStockoutId(outStockout.getStockoutId());
                    outStockoutDetail.setStockoutDetailId(outStockout.getStockoutId() + "-" + index);
                    outStockoutDetail.setProductId(detail.getProductId());
                    outStockoutDetail.setFid(detail.getTrayCode());
                    outStockoutDetail.setAllotQuantity(BigDecimal.ZERO);
                    outStockoutDetail.setAssignNum(BigDecimal.ZERO);
                    outStockoutDetailMapper.insertOutStockoutDetail(outStockoutDetail);
                }
            }
            result.setCode(0);
            result.setMsg("操作成功！");
            insertLog("DepositOutOrder", depositOrderMsg.toString(), result.toString());
        } catch (Exception e) {
            result.setCode(1);
            result.setMsg("操作失败！" + e.getMessage());
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            insertLog("DepositOutOrderError", depositOrderMsg.toString(), result.toString() + e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 入库单回传<br />
     * @author: zyr <br/>
     * @date: 2023/8/25 10:05 <br/>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void backtoInOrder() {
        Result result = new Result();

        String billId = backInOrderMapper.selectTop("1");
        BackInOrder backInOrder1 = new BackInOrder();
        backInOrder1.setBillId(billId);
        List<BackInOrder> backInOrderList = backInOrderMapper.selectBackInOrderList(backInOrder1);
        if (backInOrderList.size() != 0) {

            BackInOrders backInOrders = new BackInOrders();
            backInOrders.setBillId(backInOrderList.get(0).getBillId());
            // backInOrders.setBillType(backInOrderList.get(0).getBillType());
            // 试试写死 看能不能回传
            backInOrders.setBillType("purchase_receipt");
            ArrayList<BackInorderDetail> list = new ArrayList<>();
            for (BackInOrder backInOrder : backInOrderList) {
                BackInorderDetail backInorderDetail = new BackInorderDetail();
                backInorderDetail.setSku(backInOrder.getSku());
                backInorderDetail.setLotNo(backInOrder.getLotNo());
                BigDecimal qty = backInOrder.getQty();
                BigDecimal qtyy = qty.setScale(3, RoundingMode.HALF_UP);
                backInorderDetail.setQty(qtyy);
                list.add(backInorderDetail);
            }
            backInOrders.setDetails(list);

            BackResult backResult = null;
            try {
                String jsonesult = restTemplate.postForObject("http://172.21.4.143/iWMSopenapi/router?method=SyncOnToLocConfirm" +
                                "&timestamp=" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "&format=json" +
                                "&app_key=4d1d598839c2a574cdf2ae0f9afb313e_WCS&v=2.0&sign_method=md5&customerId=c1454398298890_WCS"
                        , backInOrders, String.class);
                backResult = JsonUtil.getObject(jsonesult, BackResult.class);

                result.setCode(backResult.getCode());
                result.setMsg(backResult.getMessage());
                insertLog("backtoInOrder", backInOrders.toString(), backResult.toString());
            } catch (RestClientException e) {
                e.printStackTrace();
                insertLog("backtoInOrderError", backInOrders.toString(), backResult.toString());
            }
            if (backResult.getCode() == 0) {
                backInOrder1.setStatus("2");
                backInOrder1.setBackTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                backInOrder1.setBackMsg(backResult.getMessage());
                backInOrderMapper.updateBackInOrder(backInOrder1);
            }else{
                backInOrder1.setStatus("3");
                backInOrder1.setBackTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                backInOrder1.setBackMsg(backResult.getMessage());
                backInOrderMapper.updateBackInOrder(backInOrder1);

            }
        }

    }

    /**
     * @Description: 出库单回传<br />
     * @author: zyr <br/>
     * @date: 2023/8/28 8:59 <br/>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void backtOutOrder() {
        Result result = new Result();

        String billId = backInOrderMapper.selectTop("2");
        BackInOrder backInOrder1 = new BackInOrder();
        backInOrder1.setBillId(billId);
        backInOrder1.setFlag("2");
        List<BackInOrder> backInOrderList = backInOrderMapper.selectBackInOrderList(backInOrder1);
        if (backInOrderList.size() != 0) {

            BackInOrders backInOrders = new BackInOrders();
            backInOrders.setBillId(backInOrderList.get(0).getBillId());
            backInOrders.setBillType(backInOrderList.get(0).getBillType());
            ArrayList<BackInorderDetail> list = new ArrayList<>();
            for (BackInOrder backInOrder : backInOrderList) {
                BackInorderDetail backInorderDetail = new BackInorderDetail();
                backInorderDetail.setSku(backInOrder.getSku());
                backInorderDetail.setLotNo(backInOrder.getLotNo());
                backInorderDetail.setQty(backInOrder.getQty());
                list.add(backInorderDetail);
            }
            backInOrders.setDetails(list);

            BackResult backResult = null;
            String jsonesult = "";
            try {
                jsonesult = restTemplate.postForObject("http://172.21.4.143/iWMSopenapi/router?method=SyncMoveLocConfirm" +
                                "&timestamp=" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "&format=json" +
                                "&app_key=4d1d598839c2a574cdf2ae0f9afb313e_WCS&v=2.0&sign_method=md5&customerId=c1454398298890_WCS"
                        , backInOrders, String.class);
                backResult = JsonUtil.getObject(jsonesult, BackResult.class);
                insertLog("backtOutOrder", backInOrders.toString(), backResult.toString());
                result.setCode(backResult.getCode());
                result.setMsg(backResult.getMessage());

            } catch (RestClientException e) {
                insertLog("backtOutOrderError", backInOrders.toString(), backResult.toString());
                e.printStackTrace();
            }
            if (backResult.getCode() == 0) {
                backInOrder1.setStatus("2");
                backInOrder1.setBackTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                backInOrder1.setBackMsg(backResult.getMessage());
                backInOrderMapper.updateBackInOrder(backInOrder1);
            }else{
                backInOrder1.setStatus("3");
                backInOrder1.setBackTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                backInOrder1.setBackMsg(backResult.getMessage());
                backInOrderMapper.updateBackInOrder(backInOrder1);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result getProductMap(ProductMapMsg productMapMsg) {
        Result result = new Result();
        try{


            for(String productDeatilId:productMapMsg.getProductDeailId()){
                ProductMap productMap = new ProductMap();

                productMap.setProductId(productMapMsg.getProductId());
                productMap.setProductDetailId(productDeatilId);
                ProductMap productMap1 = productMapMapper.selectProductMapByDetailAndPro(productMap);

                if(productMap1==null){
                    productMap.setId(UUID.randomUUID().toString());
                    productMapMapper.insertProductMap(productMap);
                }

            }

            result.setCode(0);
            result.setMsg("操作成功！");
            insertLog("productMapInterface",productMapMsg.toString(),result.toString() );

        }catch (Exception e){
            result.setCode(1);
            result.setMsg("操作失败！" + e.getMessage());
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            insertLog("productMapInterface", productMapMsg.toString(), result.toString() + e.getMessage());
        }


        return result;
    }

    public void insertLog(String system, String send, String result) {
        InterfaceLog interfaceLog = new InterfaceLog();
        interfaceLog.setId(UUID.randomUUID().toString());
        interfaceLog.setSystem(system);
        interfaceLog.setResult(result);
        interfaceLog.setSend(send);
        interfaceLog.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        interfaceLogMapper.insertInterfaceLog(interfaceLog);

    }

    @Override
    public InventoryRespond getInventoryInfo(InventoryRequest inventoryRequest) {
        InventoryRespond inventoryRespond = new InventoryRespond();
        try {
            if (StringUtils.isBlank(inventoryRequest.getProductId())){
                inventoryRespond.setCode("1");
                inventoryRespond.setMessage("物料编码不可为空");
                insertLog("getInventoryInfo", inventoryRequest.toString(), inventoryRespond.toString());
            }
            //查询库存信息
            BasStock basStock = new BasStock();
            basStock.setProductId(inventoryRequest.getProductId());
            basStock.setLotNo(inventoryRequest.getLotNo());
            basStock.setProductStatus(String.valueOf(inventoryRequest.getProductStatus()));
            List<InventoryRespondData> inventoryRespondData = basStockService.selectBasStockListForApi(basStock);

            inventoryRespond.setCode("0");
            inventoryRespond.setMessage("操作成功！");
            inventoryRespond.setData(inventoryRespondData);
//            insertLog("getInventoryInfo", inventoryRequest.toString(), inventoryRespond.toString());
        } catch (Exception e) {
            System.out.println(e);
            inventoryRespond.setCode("1");
            inventoryRespond.setMessage("操作失败！" + e.getMessage());
            Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
//            insertLog("getInventoryInfo", inventoryRequest.toString(), inventoryRespond.toString() + e.getMessage());
        }
        return inventoryRespond;
    }



    /**
     * @Description: 点收接口<br />
     * @author: zyr <br/>
     * @date: 2024/5/31 8:59 <br/>
     */
    /*@Override
    @Transactional(rollbackFor = Exception.class)
    public void checkLotNo() {

        String billId = backInOrderMapper.selectTop("1");
        BackInOrder backInOrder1 = new BackInOrder();
        backInOrder1.setBillId(billId);
    }*/




}
